#!/usr/bin/env python
import sys
import os
sys.path.append('.')
if len(sys.argv) > 1:
    os.chdir(sys.argv[1])
import marajo
import code
import boto
s3 = boto.connect_s3()
try:
    b = s3.get_bucket(marajo.config.get("s3_bucket"))
except:
    b = None
__version__ = "2.0"

def ls():
    global b
    for k in b:
        perms = "rw-"
        public = False
        acl = k.get_acl().acl
        for grant in acl.grants:
            if grant.type == "Group" and grant.email_address == None:
                public = True
        if public:
            perms += "rw-"
        else:
            perms += "---"

        print "%s %10s %s %s" % (perms, k.size, k.last_modified, k.name)

sys.ps1 = "\x01\x1b[34m\x1b[1m\x02>>> \x01\x1b[0m\x02"
sys.ps2 = "... "
banner = """Welcome to Marajo Version %s
==============================
Interactive Shell Started
b = Configured S3 Bucket
conf = marajo.config
ls() = List all files in the configured bucket
""" % __version__

if __name__ == "__main__":
    session = {}
    session['conf'] = marajo.config
    session['s3'] = s3
    session['marajo'] = marajo
    session['b'] = b
    session['ls'] = ls
    banner += "----------------------\n"
    banner += "Loaded resources\n"
    if os.path.exists("resources"):
        for obj in os.listdir("resources"):
            if "." in obj:
                name, ext = obj.split('.',1)
                if ext == "py":
                    if name == "__init__":
                        session['resources'] = __import__("resources")
                    else:
                        session[name] = getattr(__import__("resources.%s" % name), name)
                        banner += "    %s\n" % name

    code.interact(banner=banner,local=session)
